package com.jd.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jd.entity.*;
import com.jd.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jd.impl.PaymentService;
import com.jd.util.IdUtil;
import com.jd.util.OrderUtil;


@Controller
@RequestMapping("NotifyReqController")
public class NotifyReqController {
	@Autowired
    private PaymentService paymentService;
	@Autowired
    private OrderService orderService;
	@Autowired
	private NameSrevice nameService;
	@Autowired
	private UserService userService;
	@Autowired
	private DetailedService detailedService;
	@Autowired
	private TicketService ticketService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private AddressService addressService;

	@RequestMapping("NotifyReq")
	@ResponseBody
	public Map<String, String> NotifyReq(HttpServletRequest request,HttpServletResponse response){
		String userId =(String)request.getSession().getAttribute("userId");

		String price =request.getParameter("price");
		String randomNum = UUID.randomUUID().toString().replace("-", "");
		String title = "充值不凡币";
		String orderNumber = OrderUtil.getOrderIdByUUId();
		BigDecimal countPrice = BigDecimal.valueOf(Double.valueOf(price));
		//生成预订单
		OrderEntity order = new OrderEntity();
		order.setId(IdUtil.getIdByUUId());
		order.setUserId(userId);
		order.setTitle("充值不凡币");
		order.setPrice(countPrice);
		order.setOrderNumber(orderNumber);
		order.setOrderStatue("0");
		order.setOrderTime(new Date());
		order.setCreateBy(userId);
		order.setCreateTime(new Date());
		order.setDelflag("0");
		order.setType("0");
		Map<String, String> result = new HashMap<String, String>();
		Integer i = orderService.insertOrder(order);

		if(i!=0){
			try {
				result = paymentService.wxPayAssembly(userId,randomNum, title, orderNumber, countPrice,request);
				System.out.println(result+"333333333333333333333333333333333333333333");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
			/*String type =request.getParameter("type");
			//门票id
			String id =request.getParameter("id");

			//判断是实物还是门票
			if(type.equals("0")){
				NameEntity name = nameService.getName(id);
				//购买门票
				String orderNumber = OrderUtil.getOrderIdByUUId();
				String title = name.getTicket();
				String randomNum = UUID.randomUUID().toString().replace("-", "");
				double countPrice = Double.valueOf(String.valueOf(name.getPrice()));

				//生成预订单
				OrderEntity order = new OrderEntity();
				order.setNameId(id);
				order.setId(IdUtil.getIdByUUId());
				order.setUserId(userId);
				order.setTitle(title);
				order.setPrice(BigDecimal.valueOf(countPrice));
				order.setOrderNumber(orderNumber);
				order.setOrderStatue("0");
				order.setOrderTime(new Date());
				order.setCreateBy(userId);
				order.setCreateTime(new Date());
				order.setDelflag("0");
				order.setType("0");
				Map<String, String> result = new HashMap<String, String>();
				Integer i = orderService.insertOrder(order);

				if(i!=0){
					try {
						result = paymentService.wxPayAssembly(userId,randomNum, title, orderNumber, BigDecimal.valueOf(countPrice),request);
						System.out.println(result+"333333333333333333333333333333333333333333");
						return result;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				return result;
			}else{


				return null;
			}*/
	}

	/**
	 * 使用不凡币购买实物
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("goodsPay")
	@ResponseBody
	public Object goodsPay(HttpServletRequest request, HttpServletResponse response){
		Map map = new HashMap();
		try {

			String userId =(String)request.getSession().getAttribute("userId");
			//地址ID
			String addressId =request.getParameter("addressId");
			//商品id
			String goodsId =request.getParameter("goodsId");

			AddressEntity addressEntity = addressService.getById(addressId);
			GoodsEntity goodsEntity = new GoodsEntity();
			goodsEntity.setId(goodsId);
			goodsEntity = goodsService.getGoodsById(goodsEntity);

			String orderNumber = OrderUtil.getOrderIdByUUId();
			String title = goodsEntity.getName();
			double countPrice = Double.valueOf(String.valueOf(goodsEntity.getPrice()));

			HashMap<String, Object> user = userService.getUserCode(userId);
			//当前不凡币
			Double balance = Double.valueOf(user.get("mBalance").toString()) - countPrice;
			if(balance < 0){
				map.put("status",false);
				map.put("data","不凡币不足，无法兑换");
				return map;
			}

			//生成订单
			OrderEntity order = new OrderEntity();
			order.setNameId(goodsId);
			order.setId(IdUtil.getIdByUUId());
			order.setUserId(userId);
			order.setTitle(title);
			order.setPrice(BigDecimal.valueOf(countPrice));
			order.setOrderNumber(orderNumber);
			order.setOrderStatue("1");
			order.setOrderTime(new Date());
			order.setCreateBy(userId);
			order.setCreateTime(new Date());
			order.setDelflag("0");
			order.setType("0");
			order.setDelflag("0");
			order.setRemark(goodsEntity.getGoodsPic());
			order.setRemark2(addressEntity.getName());
			order.setRemark3(addressEntity.getPhone());
			order.setRemark4(addressEntity.getAddress());
			order.setRemark5("0");
			order.setRemark8("0");//实物
			order.setRemark9("1");
			order.setRemark10(goodsEntity.getPrice()+"");
			Map<String, String> result = new HashMap<String, String>();
			Integer i = orderService.insertOrder(order);
			if(i == 1){
				updateDetail(order,user);
			}
			map.put("status",true);
			map.put("data","兑换成功");
			return map;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		map.put("status",false);
		map.put("data","系统异常，请稍后再试");
		return map;
	}

	private void updateDetail(OrderEntity order, HashMap<String, Object> user) {

		DetailedEntity detailedEntity = new DetailedEntity();
		detailedEntity.setTitle("兑换"+order.getTitle());
		detailedEntity.setType("1");
		detailedEntity.setFlag("0");
		detailedEntity.setDelflag("0");

		//当前不凡币
		Double balance = Double.valueOf(user.get("mBalance").toString()) - order.getPrice().doubleValue();

		//修改钱包余额
		HashMap<String, Object> balanceMap = new HashMap<String, Object>();
		balanceMap.put("userId", order.getUserId());
		balanceMap.put("balance", balance);
		balanceMap.put("appreciating", user.get("accumulated_amount").toString());
		Boolean updateTBalance = userService.updateMBalance(balanceMap);

		//插入明细
		if (updateTBalance) {
			detailedEntity.setMoney(order.getPrice());//消费的不凡币数量
			detailedEntity.setId(IdUtil.getIdByUUId());
			detailedEntity.setUserId(order.getUserId());
			detailedEntity.setOperationTime(new Date());
			detailedEntity.setCreateBy(order.getUserId());
			detailedEntity.setCreateTime(new Date());
			detailedService.save(detailedEntity);
		}
	}

	@RequestMapping("/menpiaoPay")
	@ResponseBody
	private Object menpiaoPay(String nameId, HttpServletRequest request) {
		Map map = new HashMap();
		try {
			String userId =(String)request.getSession().getAttribute("userId");
			//根据订单号查询订单
			NameEntity name = nameService.getName(nameId);
			//代理直推佣金
			Double extensionOne = name.getExtensionOne();
			//推广佣金
			Double extension = name.getExtension();
			//代理佣金
			Double agent = name.getAgent();
			//青铜佣金
			Double bronze = name.getBronze();
			//白银佣金
			Double silver = name.getSilver();
			//黄金佣金
			Double gold = name.getGold();
			//白金佣金
			Double platinum = name.getPlatinum();
			//钻石佣金
			Double diamonds = name.getDiamonds();

			HashMap<String, Object> users = userService.getUserCode(userId);
			//当前不凡币
			Double balancee = Double.valueOf(users.get("mBalance").toString()) - name.getPrice().doubleValue();
			if(balancee < 0){
				map.put("status",false);
				map.put("data","不凡币不足，无法兑换");
				return map;
			}

			//生成订单
			OrderEntity order = new OrderEntity();
			order.setNameId(nameId);
			order.setId(IdUtil.getIdByUUId());
			order.setUserId(userId);
			order.setTitle(name.getTicket());
			order.setPrice(name.getPrice());
			order.setOrderNumber(OrderUtil.getOrderIdByUUId());
			order.setOrderStatue("1");
			order.setOrderTime(new Date());
			order.setCreateBy(userId);
			order.setCreateTime(new Date());
			order.setDelflag("0");
			order.setType("0");
			order.setDelflag("0");
			order.setRemark(name.getTicketPic());
			order.setRemark8("1");//门票
			order.setRemark9("1");
			order.setRemark10(name.getPrice()+"");
			Integer i = orderService.insertOrder(order);
			if(i>0){
				//添加一张门票
				String id = order.getUserId();
				MyTicketEntity myTicketEntity = new MyTicketEntity();
				myTicketEntity.setId(IdUtil.getIdByUUId());
				myTicketEntity.setUserId(id);
				myTicketEntity.setNameId(order.getNameId());
				myTicketEntity.setAccess("2");
				myTicketEntity.setUserStart("1");
				myTicketEntity.setGetTime(new Date());
				myTicketEntity.setOutTime(null);
				myTicketEntity.setCreateBy(id);
				myTicketEntity.setCreateTime(new Date());
				myTicketEntity.setDelflag("0");
				ticketService.save(myTicketEntity);
				//上级id
				String onUserId1 = userService.selectOnUserId(id);
				if(onUserId1!=null && !onUserId1.equals("")){
					HashMap<String, Object> user = userService.getUserCode(onUserId1);
					DetailedEntity detailedEntity = new DetailedEntity();
					detailedEntity.setTitle("佣金");
					detailedEntity.setType("0");
					detailedEntity.setFlag("1");
					detailedEntity.setDelflag("0");
					String identity = user.get("identity").toString();
					//代理直推
					if(identity.equals("0")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+extensionOne;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+extensionOne;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(extensionOne));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//推广
					if(identity.equals("1")){
						//推广钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+extension;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+extension;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(extension));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
						//推广员肯定有上级并且上级一定是代理
						String onUserId2 = user.get("on_user_id").toString();
						//代理余额
						balance = Double.valueOf(user.get("balance").toString())+agent;
						accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+agent;
						HashMap<String, Object> balance2Map = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId2);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateT2Balance = userService.updateTBalance(balance2Map);
						if(updateT2Balance){
							detailedEntity.setMoney(new BigDecimal(agent));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId2);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//平台推广
					//青铜会员
					if(identity.equals("3") && user.get("rank").toString().equals("0")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+bronze;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+bronze;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(bronze));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//平台推广
					//白银会员
					if(identity.equals("3") && user.get("rank").toString().equals("1")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+silver;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+silver;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(silver));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//平台推广
					//黄金会员
					if(identity.equals("3") && user.get("rank").toString().equals("2")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+gold;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+gold;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(gold));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//平台推广
					//白金会员
					if(identity.equals("3") && user.get("rank").toString().equals("3")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+platinum;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+platinum;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(platinum));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
					//平台推广
					//钻石会员
					if(identity.equals("3") && user.get("rank").toString().equals("4")){
						//钱包余额
						Double balance = Double.valueOf(user.get("balance").toString())+diamonds;
						Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString())+diamonds;
						HashMap<String, Object> balanceMap = new HashMap<String, Object>();
						balanceMap.put("onUserId1", onUserId1);
						balanceMap.put("balance", balance);
						balanceMap.put("accumulatedAmount", accumulatedAmount);
						//修改钱包余额
						Boolean updateTBalance = userService.updateTBalance(balanceMap);
						if(updateTBalance){
							detailedEntity.setMoney(new BigDecimal(diamonds));
							detailedEntity.setId(IdUtil.getIdByUUId());
							detailedEntity.setUserId(onUserId1);
							detailedEntity.setOperationTime(new Date());
							detailedEntity.setCreateBy(id);
							detailedEntity.setCreateTime(new Date());
							//插入明细
							detailedService.save(detailedEntity);
						}
					}
				}else{
					HashMap<String, Object> user = userService.getUserCode(userId);
					updateDetail(order, user);
				}
			}
			map.put("status",true);
			map.put("data","兑换成功");
			return map;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		map.put("status",false);
		map.put("data","系统异常，请稍后再试");
		return map;
	}
}
